﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Rong.EasyExcel;
using Rong.EasyExcel.Models;
using Simple.Services.System.FileInfo.Models;
using Simple.Services.System.Office.Model;

namespace Simple.Services.System.Office
{
    public class ExcelOperationService
    {
        private readonly IExcelExportManager _excelExportManager;
        private readonly IExcelImportManager _excelImportManager;

        public ExcelOperationService(IExcelExportManager excelExportManager, IExcelImportManager excelImportManager)
        {
            _excelExportManager = excelExportManager;
            _excelImportManager = excelImportManager;
        }

        public async Task<FileDownInputModel> ExportAsync<TExportDto>(List<TExportDto> exportList, ExportType exportType) where TExportDto : class, new()
        {
            var exportFile = new FileDownInputModel();
            var name = exportType.GetDescriptionContent();
            var bytes = await _excelExportManager.ExportAsync(exportList, opt =>
            {
                opt.ExcelType = ExcelTypeEnum.Xlsx;
                opt.SheetName = name;
            });
            exportFile.FileData = bytes;
            exportFile.FileName = $"{name}_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
            return exportFile;
        }

        public async Task<ImportExcelResultModel<TImportDto>> ImportAsync<TImportDto>(IFormFile file) where TImportDto : ImportModel, new()
        {
            var importResult = new ImportExcelResultModel<TImportDto>();
            try
            {
                var sheetList = await _excelImportManager.ImportAsync<TImportDto>(file.OpenReadStream(), opt =>
                {
                    opt.SheetIndex = 0;
                    opt.ValidateMode = ExcelValidateModeEnum.StopSheet;//可设置异常处理模式
                });
                //获取错误信息，若无错误则返回null
                importResult.Error = sheetList.GetErrorMessage();

                //获取有效数据
                importResult.ValidList = sheetList.GetValidData()?.ToList();

                // 获取无效数据
                if (!string.IsNullOrWhiteSpace(importResult.Error))
                {
                    importResult.InvalidList = new List<TImportDto>();
                    foreach (var sheet in sheetList)
                    {
                        foreach (var row in sheet.Rows.Where(s => !s.IsValid))
                        {
                            row.Row.Error = row.GetErrorMessage();
                            row.Row.RowNumber = row.RowNum;
                            importResult.InvalidList.Add(row.Row);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw AppResultException.Status400BadRequest(ex.Message);
            }
            // 如果无错误也无正确数据，说明这个导入的文件可能有问题
            if (string.IsNullOrWhiteSpace(importResult.Error) && (importResult.ValidList == null || !importResult.ValidList.Any()))
            {
                throw AppResultException.Status400BadRequest("读取不到Excel文件中指定的数据，请检查Excel文件是否符合模板要求");
            }
            // 错误已经在每一行内
            importResult.Error = null;

            return importResult;
        }
    }
}
